<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form :model="queryParams" :inline="true" label-width="100px">
          <div class="form-row">
            <el-form-item label="项目名称:">
              <el-input
                v-model="queryParams.PName"
                clearable
                style="width: 177px"
                placeholder="请输入平台类型"
              />
            </el-form-item>
            <el-form-item label="客户单位:">
              <!-- <el-select
                clearable
                style="width: 177px"
                @change="handleCustomerChange"
                v-model="queryParams.customer"
                placeholder="请选择客户单位"
              >
                <el-option
                  v-for="item in customerUnits"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select> -->
              <el-input
                v-model="queryParams.customer"
                style="width: 177px"
                placeholder="请输入客户单位"
              />
            </el-form-item>
            <el-form-item label="合同编码:">
              <el-input
                v-model="queryParams.no"
                clearable
                style="width: 177px"
                placeholder="请输入平台类型"
              />
            </el-form-item>
            <el-form-item label="项目状态:">
              <el-select
                v-model="queryParams.prStatus"
                clearable
                placeholder="请选择"
                style="width: 177px"
                @change="handleStatusChange"
              >
                <el-option
                  v-for="item in projectStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
              >搜索</el-button>
              <el-button
                icon="el-icon-refresh"
                @click="resetQuery"
              >重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <div>
        <!-- 顶部操作按钮 -->
        <div class="operation-container">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <!-- <el-button type="success" icon="el-icon-back" size="small"
            >撤回</el-button
          > -->
        </div>

        <!-- 表格 -->
        <el-table
          v-loading="loading"
          :data="expenseList"
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          />
          <el-table-column
            prop="no"
            label="合同编号"
            width="100"
          />
          <el-table-column
            prop="pname"
            label="项目名称"
            min-width="250"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="customer"
            label="客户单位"
            min-width="200"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="money"
            label="合同金额（元）"
            width="120"
            align="center"
          />
          <el-table-column
            prop="salesman"
            label="项目负责人"
            width="100"
            align="center"
          />
          <el-table-column
            prop="isProject"
            label="项目状态"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag :type="getProjectStatusType(scope.row.prStatus)">
                {{ getProjectStatus(scope.row.prStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button
                type="success"
                size="small"
                :disabled="Number(scope.row.prStatus) > 4"
                @click="handleFill(scope.row)"
              >填报</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
          <el-pagination
            background
            :current-page="queryParams.page"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </el-card>

    <!-- 添加项目办结弹框 -->
    <el-dialog
      title="项目办结"
      :visible.sync="dialogVisible"
      width="87%"
      @close="handleDialogClose"
    >
      <!-- 项目标题和折叠面板 -->
      <div class="dialog-content-wrapper">
        <div class="collapse-header">
          <h3>北仑区传媒中心经营项目立项</h3>
          <!-- <span class="view-btn">点击查看</span> -->
        </div>
        <el-card>
          <!-- <div slot="header"></div> -->
          <div>
            <div class="detail-content">
              <div class="contract-no">
                合同编号：{{ projectDetail.no || "" }}
              </div>
              <el-form label-width="100px" class="detail-form">
                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目名称">
                      <el-input
                        v-model="projectDetail.pname"
                        disabled
                        style="width: 100%"
                        :class="{
                          'modified-field': isFieldModified('pname'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目采购方式">
                      <el-input
                        v-model="projectDetail.projectFrom"
                        disabled
                        style="width: 100%"
                        :class="{
                          'modified-field': isFieldModified('projectFrom'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="客户类型">
                      <el-input
                        v-model="projectDetail.customerType"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('customerType'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户单位">
                      <el-input
                        v-model="projectDetail.customer"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('customer'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目领域">
                      <el-input
                        v-model="projectDetail.projectArea"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('projectArea'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目负责人">
                      <el-input
                        v-model="projectDetail.salesman"
                        style="width: 100%"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('salesman'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="存量类型">
                      <el-input
                        v-model="projectDetail.stockType"
                        disabled
                        style="width: 100%"
                        :class="{
                          'modified-field': isFieldModified('stockType'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执行时间">
                      <el-input
                        v-model="projectDetail.duration"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('duration'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目成本">
                      <el-input
                        v-model="projectDetail.cost"
                        style="width: 100%"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('cost'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同金额">
                      <el-input
                        v-model="projectDetail.money"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('money'),
                        }"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="实际收入">
                      <el-input
                        v-model="projectDetail.income"
                        style="width: 100%"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('income'),
                        }"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否到账">
                      <el-input
                        v-model="projectDetail.isAccount"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('isAccount'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="到账金额">
                      <el-input
                        v-model="projectDetail.receiveMoney"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('receiveMoney'),
                        }"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目奖励">
                      <el-input
                        v-model="projectDetail.manageRate"
                        disabled
                        :class="{
                          'modified-field': isFieldModified('manageRate'),
                        }"
                      >
                        <template slot="append">%</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="24">
                    <el-form-item label="内容及要求">
                      <el-input
                        v-model="projectDetail.content"
                        type="textarea"
                        :rows="4"
                        disabled
                        :class="{
                          'content-modified': isFieldModified('content'),
                        }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-card>
        <!-- 项目基本信息表单 -->
        <el-card style="margin-top: 20px">
          <div>
            <div class="project-type">
              <div class="type-title">项目类型</div>
              <el-table
                :header-cell-style="{ background: '#f5f7fa' }"
                :data="projectDetail.projectDetails || []"
                border
                style="width: 100%"
              >
                <el-table-column
                  prop="platform"
                  label="平台产品IP"
                  width="150"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span :style="getDifferentStyle('platform', scope.$index)">
                      {{ scope.row.platform || "无" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="department"
                  label="执行事业部"
                  width="200"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span
                      :style="getDifferentStyle('department', scope.$index)"
                    >
                      {{ scope.row.department }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="content"
                  label="执行内容及要求"
                  width="300"
                  align="center"
                  show-overflow-tooltip
                >
                  <template slot-scope="scope">
                    <span :style="getDifferentStyle('content', scope.$index)">
                      {{ scope.row.content || "无" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="attribute"
                  label="属性"
                  align="center"
                  width="width"
                >
                  <template slot-scope="scope">
                    <span :style="getDifferentStyle('attribute', scope.$index)">
                      {{ scope.row.attribute || "无" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="money"
                  label="金额"
                  align="center"
                  width="width"
                >
                  <template slot-scope="scope">
                    <span :style="getDifferentStyle('money', scope.$index)">
                      {{ scope.row.money || "0" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="estimatedCost"
                  label="成本"
                  align="center"
                  width="width"
                >
                  <template slot-scope="scope">
                    <span
                      :style="getDifferentStyle('estimatedCost', scope.$index)"
                    >
                      {{ scope.row.estimatedCost || "0" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferCompany"
                  label="划转对象"
                  align="center"
                  width="width"
                >
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.transferCompany"
                      clearable
                      :style="
                        getDifferentStyle('transferCompany', scope.$index)
                      "
                      placeholder="请选择划转对象"
                      size="small"
                      style="width: 100%"
                      @change="handleTransferCompanyChange($event, scope.row)"
                    >
                      <el-option
                        v-for="item in transferObjectList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferMoney"
                  label="划转金额"
                  align="center"
                  width="width"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.transferMoney"
                      placeholder="请输入划转金额"
                      clearable
                      :style="getDifferentStyle('transferMoney', scope.$index)"
                      @change="handleTransferMoneyChange($event, scope.row)"
                    >
                      {{ scope.row.transferMoney || "0" }}
                    </el-input>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="transferExplain" label="划转说明">
                  <template slot-scope="scope">
                    {{ scope.row.transferExplain || "0" }}
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
          </div>
        </el-card>
        <!-- 计财部填报表单 -->
        <el-card style="margin-top: 20px">
          <div style="border: 2px solid #ebeef5">
            <div class="contract-info">
              <div class="info-item">
                <div class="info-label">合同电子版</div>
                <div class="info-content">
                  <a
                    v-if="projectDetail.contractFile"
                    :href="projectDetail.contractFile"
                    class="download-link"
                    @click.prevent="
                      handleFileDownload(projectDetail.contractFile)
                    "
                  >
                    {{ getFileName(projectDetail.contractFile) }}(点击下载文件)
                  </a>
                  <div class="button-group">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleFileDownload(projectDetail.contractFile)"
                    >下载</el-button>
                    <el-button
                      size="small"
                      @click="handlePreview"
                    >预览</el-button>
                  </div>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">负责人备注</div>
                <div class="info-content">
                  {{ projectDetail.remarks || "" }}
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">完成概述</div>
                <div class="info-content">
                  {{ projectDetail.describe || "" }}
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">结案人</div>
                <div class="info-content">
                  {{ projectDetail.createName || projectDetail.salesman }}
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">结案时间</div>
                <div class="info-content">
                  {{ formatCreateTime(projectDetail.endCreateTime) || "" }}
                </div>
              </div>
              <!-- <div class="info-item">
                <div class="info-label">客户满意度</div>
                <div class="info-content">
                  {{ projectDetail.satisfaction || "" }}
                </div>
              </div> -->
              <div class="info-item">
                <div class="info-label">融合发展事业部意见</div>
                <div class="info-content">
                  {{ projectDetail.rmSuggest || "" }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 计财部填报表单 -->
      <el-card style="margin-top: 20px">
        <div slot="header" class="type-title">费用测算</div>

        <el-form
          ref="formRef"
          :model="financeForm"
          label-width="160px"
          class="finance-form"
        >
          <el-form-item label="合同金额">
            <span class="amount">{{ financeRow.money || "" }}元</span>
          </el-form-item>

          <el-form-item label="合同收入">
            <span class="amount">{{ financeRow.income }}元</span>
          </el-form-item>

          <el-form-item label="项目奖励比例">
            <!-- <div class="input-group"> -->
            <el-input
              v-model="financeForm.managementRate"
              style="width: 50%"
              placeholder="请输入项目奖励比例"
              @input="handleManagementRateInput"
            >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>

          <el-form-item label="项目奖励金额">
            <div class="input-group">
              <el-input
                v-model="financeForm.manageMoney"
                style="width: 50%"
                placeholder="请输入项目奖励金额"
                disabled
              >
                <template slot="append">元</template>
              </el-input>

              <el-button
                type="primary"
                class="calc-btn"
                @click="calculateManagementAward"
              >
                计算
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="划转对象项目实际金额">
            <!-- <div class="input-group"> -->
            <el-input
              v-model="financeForm.taxInclusivePrice"
              style="width: 50%"
              placeholder="请输入划转对象项目实际金额"
            >
              <template slot="append">元</template>
            </el-input>
            <!-- </div> -->
          </el-form-item>
        </el-form>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selCostListApi, addCostCountByIdApi } from '@/api/close_case'
import {
  selTaxRateListApi,
  selCustomerUnitListApi,
  selTransferObjectListApi
} from '@/api/basic-data'
import { selFileUrlApi } from '@/api/uploadFile'
import { mapGetters } from 'vuex'
export default {
  name: 'Expense',
  data() {
    return {
      tableData: [
        {
          id: 1,
          contractNo: '202412111',
          projectName: '北仑区纪律检查委员会（党风廉政建设专项片）',
          customerUnit: '中国共产党宁波市北仑区纪律检查委员会',
          contractAmount: 200000,
          projectManager: '张强',
          status: '待填报',
          createTime: '2024-12-11 09:44'
        },
        {
          id: 2,
          contractNo: '202406203',
          projectName: '宁波经济技术开发商务局年度宣传合作协议',
          customerUnit: '宁波经济技术开发商务局',
          contractAmount: 76623,
          projectManager: '田琦、陈建伟',
          status: '待填报',
          createTime: '2024-06-20 00:00'
        },
        {
          id: 3,
          contractNo: '202406202',
          projectName: '宁波保税区市场发展有限公司年度视频宣传合作协议',
          customerUnit: '宁波保税区市场发展有限公司',
          contractAmount: 80000,
          projectManager: '田琦',
          status: '待填报',
          createTime: '2024-06-20 15:07'
        },
        {
          id: 4,
          contractNo: '202404244',
          projectName: '大碶街道杨古农文服活动线上宣传',
          customerUnit: '宁波市北仑区大碶街道办事处',
          contractAmount: 16800,
          projectManager: '虞夕红',
          status: '待填报',
          createTime: '2024-04-24 15:49'
        },
        {
          id: 5,
          contractNo: '202404071',
          projectName: '2024年区政协年度宣传合作协议',
          customerUnit: '政协宁波市北仑区委员会办公室',
          contractAmount: 100000,
          projectManager: '舒一展',
          status: '待填报',
          createTime: '2024-04-07 14:22'
        },
        {
          id: 6,
          contractNo: '202403181',
          projectName: '2024年《山海经》栏目合作协议',
          customerUnit: '宁波市北仑区人民医院',
          contractAmount: 140000,
          projectManager: '谢俊杰',
          status: '待填报',
          createTime: '2024-03-18 09:23'
        }
      ],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        customer: '',
        no: '',
        PName: '',
        prStatus: 1
      },
      pid: '',
      expenseList: [], // 费用测算列表
      taxRateList: [], // 税率列表
      total: 0,
      // 项目状态
      projectStatus: [
        { label: '待填报', value: 1 },
        { label: '已填报', value: 2 }
      ],
      isFilterVisible: false,
      dialogVisible: false,
      activeCollapse: [],
      // 税率列表查询参数
      selTaxRateQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      projectInfo: {
        name: '北仑区纪律检查委员会《党风廉政建设专题片》',
        executeTime: '2024-12-13至2025-01-24',
        customerType: '政府',
        customerUnit: '中国共产党宁波市北仑区纪律检查委员会',
        projectField: '党建群团',
        stockType: '存量',
        isKeyProject: '否',
        contractAmount: '200000',
        manager: '张强',
        manageMoney: '2',
        requirements:
          '1、甲方委托乙方拍摄制作《党风廉政建设专题片》一部，时长23分钟左右，根据实际情况确定。\n2、根据片子要求，乙方实行保密措施，确保文稿、镜头、配音等相关素材等不流传摄制组之外。'
      },
      projectTypeList: [
        {
          productIp: '*视频',
          department: '视觉影像事业部',
          requirements:
            '1、甲方委托乙方拍摄制作《党风廉政建设专题片》一部，时长23分钟左右，根据实际情况确定。2、根据片子要求，乙方实行保密措施...',
          property: '执行类',
          amount: '200000',
          directCost: '0',
          transferCompany: '无',
          taxInclusivePrice: '0',
          transferNote: ''
        }
      ],
      completionInfo: [
        {
          wordContract:
            '中共宁波市北仑纪律检查委员会视频摄制合作协议(1)(2).doc(点击下载文件)',
          remark: '备注',
          completionDesc:
            '按要求拍摄制作完成《党风廉政建设专题片》一部，时长20分钟。',
          closePerson: '张强',
          closeDate: '2025-02-05',
          customerSatisfaction: '满意',
          serviceOpinion: '同意'
        }
      ],
      formData: {
        contractAmount: '200000',
        taxRate: '6',
        contractTax: '11321',
        contractCost: '',
        contractIncome: '',
        remark: ''
      },
      // 审核合同表单数据
      financeForm: {
        list: [],
        managementRate: '', // 项目项目奖励
        manageMoney: '', // 项目管理奖
        taxInclusivePrice: '', // 划转对象项目实际金额
        userId: this.$store.getters.userId // string 人员id
      },
      // 客户类型列表参数
      selCustomerTypeListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      expenseForm: {
        cost: null, // number(double) 成本
        income: null, // number(double) 收入
        remark: '', // string 备注
        result: '', // string 是否同意
        tax: null, // number(double) 税金
        taxRate: null, // number(double) 税率
        userId: this.$store.getters.userId // string 人员id
      },
      financeRow: {}, // 财务审核行数据
      projectDetail: {}, // 项目基本信息行数据
      customerUnits: [], // 客户单位列表
      modifiedRecords: [], // 添加修改记录数组
      modifiedIds: [] // 添加被修改的数据ID列表
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    if (this.$route.query.no) {
      this.queryParams.no = this.$route.query.no
    }
    this.selCostList()
    this.selTaxRateList()
    this.selCustomerUnitList()
    this.selTransferObjectList()
  },
  methods: {
    // 划转对象列表查询
    async selTransferObjectList() {
      const res = await selTransferObjectListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.transferObjectList = res.records
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return ''
      // 截取_后面的部分作为文件名
      console.log(url.split('_').pop())
      return url.split('_').pop()
    },
    // 处理文件下载
    handleFileDownload(url) {
      if (!url) {
        this.$message.warning('文件链接不存在')
        return
      }

      // 拼接完整的下载地址
      // const baseUrl = "http://192.168.11.22:38085";
      const baseUrl = 'http://192.168.11.2:8081'
      const fullUrl = `${baseUrl}${url}`

      // 获取文件名 - 截取_后面的部分
      const fileName = url.split('_').pop()
      console.log(fullUrl)

      try {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = fullUrl
        link.setAttribute('download', fileName) // 使用新的文件名
        document.body.appendChild(link)

        link.click()

        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      }
    },
    // 处理文件预览
    async handlePreview() {
      if (!this.projectDetail.contractFile) {
        this.$message.warning('文件链接不存在')
        return
      }
      try {
        // 获取预览链接
        const res = await selFileUrlApi(this.projectDetail.contractFile)
        console.log(res)
        if (res.code === 1 && res.data) {
          // 在新窗口中打开预览链接
          window.open(res.data, '_blank')
        } else {
          this.$message.error(res.msg || '获取预览链接失败')
        }
      } catch (error) {
        console.error('预览失败:', error)
        this.$message.error('预览失败，请重试')
      }
    },
    // 处理客户单位变化
    handleCustomerChange(val) {
      console.log(val)
      this.selCostList()
    },
    // 客户单位列表查询
    async selCustomerUnitList() {
      const res = await selCustomerUnitListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.customerUnits = res.records
    },
    // 财务审核列表查询
    async selCostList() {
      this.loading = true
      try {
        const res = await selCostListApi(this.queryParams)
        console.log('selCostList response:', res) // 添加日志
        if (res.records && res.records.length) {
          this.expenseList = res.records[0]
          this.total = res.total
          // 第二个数组是修改记录
          this.modifiedRecords = res.records[1]
          console.log('modifiedRecords after API call:', this.modifiedRecords) // 添加日志
          // 获取被修改的数据ID列表
          this.modifiedIds = this.modifiedRecords.map((item) => item.id)
        }
      } catch (error) {
        console.error('查询失败:', error)
        this.$message.error('查询失败，请重试')
      } finally {
        this.loading = false
      }
    },
    // 税率列表查询
    async selTaxRateList() {
      const res = await selTaxRateListApi(this.selTaxRateQuery)
      console.log('res', res)
      this.taxRateList = res.records
    },
    // 划转对象变化
    handleTransferCompanyChange(value, row) {
      console.log('划转对象变化', value, row)
      const index = this.financeForm.list.findIndex(
        (item) => item.id === row.id
      )
      console.log(index)

      if (index > -1) {
        this.financeForm.list[index].transferCompany = value || '无'
      }
    },
    // 处理划转金额变化
    handleTransferMoneyChange(value, row) {
      console.log('划转金额变化', value, row)
      const index = this.financeForm.list.findIndex(
        (item) => item.id === row.id
      )
      console.log(index)

      if (index > -1) {
        // 将输入值转换为数字类型
        const numValue = value === '' ? 0 : Number(value)
        if (isNaN(numValue)) {
          this.$message.warning('请输入有效的数字')
          return
        }
        this.financeForm.list[index].transferMoney = numValue
      }
    },
    // 添加新方法来检查字段是否被修改
    isFieldModified(key, rowIndex) {
      const currentId = this.projectDetail.id
      const modifiedData = this.modifiedRecords?.find(
        (item) => item.id === currentId
      )

      if (modifiedData) {
        if (rowIndex !== undefined) {
          // 处理数组数据
          const currentDetails = this.projectDetail.projectDetails
          const modifiedDetails = modifiedData.projectDetails

          // 如果当前详情存在且行索引超出修改后的详情长度
          if (
            currentDetails &&
            modifiedDetails &&
            rowIndex >= modifiedDetails.length
          ) {
            return true // 新行应该显示为红色
          }

          // 比较现有行
          if (
            currentDetails &&
            modifiedDetails &&
            currentDetails[rowIndex] &&
            modifiedDetails[rowIndex]
          ) {
            return (
              currentDetails[rowIndex][key] !== modifiedDetails[rowIndex][key]
            )
          }
        } else {
          // 处理普通字段
          return modifiedData[key] !== this.projectDetail[key]
        }
      }
      return false
    },
    // 更新 getDifferentStyle 方法
    getDifferentStyle(key, rowIndex) {
      return this.isFieldModified(key, rowIndex) ? { color: 'red' } : {}
    },
    // 项目状态
    handleStatusChange(val) {
      if (val === '') {
        this.queryParams.prStatus = 1
      }
      console.log(val)
      this.selCostList()
    },
    // 搜索
    handleQuery() {
      this.queryParams.page = 1
      this.selCostList()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        page: 1,
        pageSize: 10,
        customer: '',
        no: '',
        PName: '',
        prStatus: 1
      }
      this.selCostList()
    },
    // 分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.selCostList()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.selCostList()
    },
    // 填报
    handleFill(row) {
      console.log('handleFill row:', row) // 添加日志
      // 显示对话框
      this.dialogVisible = true
      // 设置项目ID
      this.pid = row.id
      // 保存项目详情
      this.projectDetail = row
      // 保存财务行数据
      this.financeRow = row
      this.financeForm.managementRate = row.manageRate

      console.log('projectDetail:', this.projectDetail) // 添加日志
      console.log('modifiedRecords:', this.modifiedRecords) // 添加日志

      if (row.projectDetails && Array.isArray(row.projectDetails)) {
        this.financeForm.list = row.projectDetails.map((item) => ({
          id: item.id,
          transferCompany: item.transferCompany || '无',
          transferMoney: Number(item.transferMoney || 0)
        }))
      }
    },
    handleDialogClose() {
      this.$refs.formRef?.resetFields()
      this.dialogVisible = false
    },

    // 封装获取项目状态
    getProjectStatus(status) {
      if (status === null || status === undefined) return ''

      const statusNum = Number(status)
      if (statusNum > 4) {
        return '已填报'
      } else if (statusNum <= 4) {
        return '待填报'
      }
      return ''
    },
    // 封装获取项目状态类型
    getProjectStatusType(status) {
      if (status === null || status === undefined) return ''

      const statusNum = Number(status)
      if (statusNum > 4) {
        return 'success' // 绿色
      } else if (statusNum <= 4) {
        return 'warning' // 黄色
      }
      return 'info' // 默认灰色
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 处理项目项目奖励输入
    handleManagementRateInput(value) {
      // 清除非数字字符
      let newValue = value.replace(/[^\d.]/g, '')

      // 限制只能输入一个小数点
      if ((newValue.match(/\./g) || []).length > 1) {
        newValue = newValue.replace(/\.+$/, '')
      }

      // 限制小数点后两位
      if (newValue.includes('.')) {
        const parts = newValue.split('.')
        if (parts[1].length > 2) {
          newValue = parts[0] + '.' + parts[1].slice(0, 2)
        }
      }

      this.financeForm.managementRate = newValue
    },

    // 计算项目管理奖
    calculateManagementAward() {
      // 移除空值判断，只判断是否为数字且不小于0
      const rate = parseFloat(this.financeForm.managementRate)
      if (isNaN(rate) || rate < 0) {
        this.$message.warning('请输入有效的项目项目奖励')
        return
      }

      // 项目管理奖 = 合同金额 * 比例
      const award = this.financeRow.money * (rate / 100)

      // 如果是整数，不显示小数点后的零
      this.financeForm.manageMoney =
        award % 1 === 0
          ? Math.floor(award).toString()
          : award.toFixed(2).replace(/\.?0+$/, '')

      console.log('计算结果:', this.financeForm.manageMoney) // 添加调试日志
    },

    // 提交表单
    async handleSubmit() {
      try {
        if (
          this.financeForm.managementRate === '' ||
          !this.financeForm.manageMoney
        ) {
          this.$message.warning('请完成项目奖励的计算')
          return
        }

        if (this.financeForm.taxInclusivePrice === '') {
          this.$message.warning('请输入划转对象项目实际金额')
          return
        }

        // const submitData = {
        //   manageMoney: parseFloat(this.financeForm.manageMoney),
        //   taxInclusivePrice: parseFloat(this.financeForm.taxInclusivePrice),
        // };

        // 这里添加你的提交逻辑
        // console.log("提交数据:", submitData, this.pid);
        const res = await addCostCountByIdApi(this.financeForm, this.pid)
        if (res.code === 1) {
          this.$message.success('提交成功')
          this.dialogVisible = false
          this.financeForm = {}
          this.selCostList()
        } else {
          this.$message.error(res.msg || '提交失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('提交失败，请重试')
      }
    },
    previewFile(row) {
      // 处理文件预览逻辑
      console.log('预览文件：', row.wordContract)
    }
  }
}
</script>

<style lang="scss">
.app-container {
  padding: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.operation-container .el-button {
  margin-right: 10px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.search-wrapper {
  margin-bottom: 20px;
}

/* 确保表格内容不会被截断 */
.el-table .cell {
  white-space: nowrap;
}

/* 调整按钮样式 */
.el-button--text {
  padding: 0;
  margin: 0;
}

/* 调整表格行高 */
.el-table td {
  padding: 8px 0;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 项目标题样式 */
.project-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 14px;
}

.view-text {
  color: #409eff;
  font-size: 13px;
}

/* 折叠面板样式 */
:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  background-color: #f5f7fa;
  padding: 12px 20px;
  border: none;
}

:deep(.el-collapse-item__content) {
  padding: 0;
}

/* 项目详情样式 */
.project-detail {
  padding: 20px;
  background-color: #fafafa;
}

.contract-number {
  font-size: 14px;
  color: #409eff;
  margin-bottom: 20px;
}

.project-form {
  margin-bottom: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #303133;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #303133;
}

/* 表单样式 */
.expense-form {
  padding: 20px;
}

.finance-form {
  max-width: 800px;
}

/* 输入框组样式 */
.input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.unit {
  margin: 0 8px;
  color: #606266;
}

.calc-btn {
  margin-left: 8px;
}

/* 金额显示样式 */
.amount {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 25px;
}

.file-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-name {
  color: #409eff;
  cursor: pointer;
}

.person-cell {
  display: flex;
  flex-direction: column;
}

.close-date {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 调整表格内容的垂直对齐方式 */
:deep(.el-table__cell) {
  vertical-align: middle;
}

/* 确保表格内的按钮垂直居中 */
:deep(.el-button--mini) {
  margin: 0;
}

/* 调整输入框后缀样式 */
:deep(.el-input-group__append) {
  background-color: #f5f7fa;
  color: #909399;
  border-left: 1px solid #dcdfe6;
  padding: 0 15px;
}

.collapse-header {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #303133;

  .view-btn {
    color: #409eff;
    font-size: 14px;
    cursor: pointer;
  }
}

.detail-content {
  background: #fff;
  // border: 2px solid #ebeef5;
  // margin-top: 20px;

  .contract-no {
    color: #1b86ee;
    font-size: 16px;
    margin: 20px;
  }
}

.project-type {
  margin-top: 20px;

  .type-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 4px solid #409eff;
  }

  :deep(.el-table) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      padding: 8px 0;
      font-weight: normal;
    }

    td {
      padding: 8px;
      color: #606266;
    }

    &::before,
    &::after {
      background-color: #ebeef5;
    }

    .el-table__cell {
      border-color: #ebeef5;
    }
  }

  .contract-info {
    // margin-top: 40px;
    // border: 2px solid #ebeef5;
    border-radius: 4px;

    .info-item {
      display: flex;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .info-label {
        width: 120px;
        padding: 12px;
        background-color: #f5f7fa;
        color: #606266;
        font-size: 14px;
        border-right: 1px solid #ebeef5;
      }

      .info-content {
        flex: 1;
        padding: 12px;
        min-height: 44px;
        display: flex;
        align-items: center;
        color: #606266;
        font-size: 14px;

        &:has(.download-link) {
          justify-content: space-between;
        }

        .download-link {
          color: #409eff;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }

        .button-group {
          .el-button {
            margin-left: 10px;
          }
        }
      }
    }
  }
}

.type-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  // margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.contract-info {
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .info-item {
    display: flex;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      width: 130px;
      padding: 12px;
      background-color: #f5f7fa;
      color: #606266;
      font-size: 14px;
      border-right: 1px solid #ebeef5;
    }

    .info-content {
      flex: 1;
      padding: 12px;
      min-height: 44px;
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;

      &:has(.download-link) {
        justify-content: space-between;
      }

      .download-link {
        color: #409eff;
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

      .button-group {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

.detail-form {
  .el-input.is-disabled.modified-field {
    .el-input__inner {
      color: red !important;
      -webkit-text-fill-color: red !important;
    }
  }
}

.detail-form {
  .el-textarea.is-disabled.content-modified {
    .el-textarea__inner {
      color: red !important;
      -webkit-text-fill-color: red !important;
    }
  }
}
</style>
